package com.jcp.baselibrary.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

/**
 * 系统工具箱
 */
public class SystemUtil {

    /**
     * 获取当前进程名
     * @param context
     * @return 进程名
     */
    public static final String getProcessName(Context context) {
        String processName = null;

        // ActivityManager
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));

        while (true) {
            for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
                if (info.pid == android.os.Process.myPid()) {
                    processName = info.processName;

                    break;
                }
            }

            // go home
            if (!TextUtils.isEmpty(processName)) {
                return processName;
            }

            // take a rest and again
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static final String getOsInfo() {
        return Build.VERSION.RELEASE;
    }

    public static final String getPhoneModelWithManufacturer() {
        return Build.MANUFACTURER + " " + Build.MODEL;
    }

    public static String getPhoneMode() {
        return Build.MODEL;
    }

    public static String getBuildVersion() {
        return Build.VERSION.RELEASE;
    }

    public static  String getPhoneInfo() {
        StringBuilder stringBuild = new StringBuilder();
        stringBuild.append("android.os.Build.MODEL：");
        stringBuild.append(android.os.Build.MODEL);// 手机型号
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.BRAND：");
        stringBuild.append(android.os.Build.BRAND);//手机品牌
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.PRODUCT：");
        stringBuild.append(android.os.Build.PRODUCT);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.CPU_ABI：");
        stringBuild.append(android.os.Build.CPU_ABI);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.TAGS：");
        stringBuild.append(android.os.Build.TAGS);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION_CODES.BASE：");
        stringBuild.append(android.os.Build.VERSION_CODES.BASE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION.SDK：");
        stringBuild.append(android.os.Build.VERSION.SDK);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.VERSION.RELEASE：");
        stringBuild.append(android.os.Build.VERSION.RELEASE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.DEVICE：");
        stringBuild.append(android.os.Build.DEVICE);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.DISPLAY：");
        stringBuild.append(android.os.Build.DISPLAY);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.FINGERPRINT：");
        stringBuild.append(android.os.Build.FINGERPRINT);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.ID：");
        stringBuild.append(android.os.Build.ID);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.MANUFACTURER：");
        stringBuild.append(android.os.Build.MANUFACTURER);
        stringBuild.append("\n");
        stringBuild.append("android.os.Build.USER：");
        stringBuild.append(android.os.Build.USER);
        return stringBuild.toString();

    }

    public static boolean FrontDesk(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    //Toast.makeText(context, "后台", Toast.LENGTH_SHORT).show();
                    return true;
                } else {
                    //Toast.makeText(context, "前台", Toast.LENGTH_SHORT).show();
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 判断程序是否在前台运行
     * @param context
     * @return true在前台，false在后台
     */
    public static final boolean isAppOnForeground(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> list = manager
                .getRunningAppProcesses();
        if (list == null)
            return false;
        boolean ret = false;
        Iterator<ActivityManager.RunningAppProcessInfo> it = list.iterator();
        while (it.hasNext()) {
            ActivityManager.RunningAppProcessInfo appInfo = it.next();
            if (appInfo.processName.equals(packageName)
                    && appInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                ret = true;
                break;
            }
        }
        return ret;
    }

    /**
     * 判断程序是否在前台运行
     * @param context
     * @return true在前台，false在后台
     */
    public static boolean isAppForeground(Context context) {
        boolean isForeground = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String pkgName : processInfo.pkgList) {
                        if (pkgName.equals(context.getPackageName())) {
                            isForeground = true;
                        }
                    }
                }
            }
        } else {
            //@deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, 从Android5.0开始不能使用getRunningTask函数
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isForeground = true;
            }
        }
        return isForeground;
    }

    public static final boolean isScreenOn(Context context) {
        PowerManager powerManager = (PowerManager) context
                .getSystemService(Context.POWER_SERVICE);
        return powerManager.isScreenOn();
    }

    public static boolean stackResumed(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = context.getApplicationContext().getPackageName();
        List<ActivityManager.RunningTaskInfo> recentTaskInfos = manager.getRunningTasks(1);
        if (recentTaskInfos != null && recentTaskInfos.size() > 0) {
            ActivityManager.RunningTaskInfo taskInfo = recentTaskInfos.get(0);
            if (taskInfo.baseActivity.getPackageName().equals(packageName) && taskInfo.numActivities > 1) {
                return true;
            }
        }

        return false;
    }

    public static final String SYS_EMUI = "sys_emui";
    public static final String SYS_MIUI = "sys_miui";
    public static final String SYS_FLYME = "sys_flyme";
    public static final String SYS_OTHER = "sys_other";
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
    private static final String KEY_EMUI_API_LEVEL = "ro.build.hw_emui_api_level";
    private static final String KEY_EMUI_VERSION = "ro.build.version.emui";
    private static final String KEY_EMUI_CONFIG_HW_SYS_VERSION = "ro.confg.hw_systemversion";

    public static String getSystem(Context context){
        String sysType = getSystemProperty(context,"sysType");
        if (TextUtils.isEmpty(sysType)) {
            try {
                sysType = SYS_OTHER;
                Properties prop = new Properties();
                prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
                if (prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                        || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                        || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null) {
                    sysType = SYS_MIUI;//小米
                } else if (prop.getProperty(KEY_EMUI_API_LEVEL, null) != null
                        || prop.getProperty(KEY_EMUI_VERSION, null) != null
                        || prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, null) != null) {
                    sysType = SYS_EMUI;//华为
                } else if (getMeizuFlymeOSFlag(context).toLowerCase().contains("flyme")) {
                    sysType = SYS_FLYME;//魅族
                }
            } catch (IOException e) {
                e.printStackTrace();
                return sysType;
            }
        }
        return sysType;
    }

    private static String getMeizuFlymeOSFlag(Context context) {
        return getSystemProperty(context, "ro.build.display.id");
    }

    private static final String getSystemProperty(Context context, String property) {
        try {
            ClassLoader cl = context.getClassLoader();
            Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
            Method method = SystemProperties.getMethod("get", String.class);
            Object[] params = new Object[1];
            params[0] = property;
            return (String)method.invoke(SystemProperties, params);
        } catch (Exception e) {
            return null;
        }
    }

}
